package com.example.demo.utils;



import com.example.demo.domain.AjaxResult;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.http.HttpMethodName;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.Date;

/**
 * 知识图谱后端文件处理工具类
 * 下载文件工具
 * @author wzh
 * @date 2025.4.16
 */

@Component
@Data
public class CosFileDownload {

    @Autowired
    private CosConfigProperties cosConfigProperties;

    @Autowired
    private COSClient cosClient;

    public AjaxResult getUrl(String filename) {
        try {
            System.out.println(filename);
            String bucketName = cosConfigProperties.getBucketName();
            String folder = cosConfigProperties.getFolder();

            // COS中的路径
            String key =  filename;

            // 生成1小时有效的临时URL
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
            URL url = cosClient.generatePresignedUrl(
                    bucketName,
                    key,
                    expiration,
                    HttpMethodName.GET
            );
            String newUrl = replacePort(url.toString(), 8081);
            System.out.println("返回的url为："+newUrl);
            return AjaxResult.success(newUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("Error generating URL");
        }
    }

    private String replacePort(String originalUrl, int newPort) {
        return originalUrl.replaceFirst(":(\\d+)", ":" + newPort);
    }

}

